﻿using System.Windows;
using System.Windows.Controls;
using System.Windows.Input;
using System.Windows.Interactivity;
using System.Windows.Media;

namespace MSPToolkit.Behaviors
{
    public class SwitchFocusOnKeyPressBehavior : Behavior<Control>
    {
        public string ControlName { get; set; }

        private Key _key = Key.Enter;
        public Key Key
        {
            get { return _key; }
            set { _key = value; }
        }

        protected override void OnAttached()
        {
            base.OnAttached();

            AssociatedObject.KeyUp += OnKeyUp;
        }

        void OnKeyUp(object sender, KeyEventArgs e)
        {
            if (e.Key == Key)
            {
                var control = FindChild(Application.Current.RootVisual, ControlName);
                if (control != null)
                    control.Focus();
            }
        }

        private Control FindChild(DependencyObject root, string childName)
        {
            if (root == null)
                return null;
            if (childName == null)
                return null;

            Control foundChild = null;

            int childrenCount = VisualTreeHelper.GetChildrenCount(root);
            for (int i = 0; i < childrenCount; i++)
            {
                var child = VisualTreeHelper.GetChild(root, i);

                var childType = child as Control;
                if (childType == null)
                {
                    foundChild = FindChild(child, childName);

                    if (foundChild != null)
                        break;
                }
                else if (!string.IsNullOrEmpty(childName))
                {
                    var frameworkElement = child as FrameworkElement;
                    if (frameworkElement != null && frameworkElement.Name == childName)
                    {
                        foundChild = (Control)child;
                        break;
                    }

                    foundChild = FindChild(child, childName);
                }
                else
                {
                    foundChild = (Control)child;
                    break;
                }
            }

            return foundChild;
        }


        protected override void OnDetaching()
        {
            base.OnDetaching();

            AssociatedObject.KeyUp -= OnKeyUp;
        }
    }
}
